package com.outlook.flowervowlogin;

import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.File;

public class CommandLogin implements CommandExecutor {
    private Main plugin;
    public CommandLogin(Main plugin){
        this.plugin = plugin;
    }
    @Override
    public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) {
        try {
            Player p = (Player) commandSender;
            if (command.getName().equalsIgnoreCase("l")) {
                if (args.length == 1) {
                    File dir = new File(Main.instance.getDataFolder(),"Player");
                    File playerfile = new File(dir,p.getName()+".yml");
                    FileConfiguration playeryml = YamlConfiguration.loadConfiguration(playerfile);
                    String password = args[0];
                    if (playerfile.exists()) {
                        if (password.equals(playeryml.get("password"))) {
                            p.sendMessage("§a[§a茶§b坂]§2登录成功！马上将您传送至大厅");
                            new BukkitRunnable(){
                                @Override
                                public void run(){
                                    ByteArrayDataOutput out = ByteStreams.newDataOutput();
                                    out.writeUTF("Connect");
                                    out.writeUTF(Main.instance.getConfig().getString("LobbyName"));
                                    p.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
                                }
                            }.runTaskLater(plugin,10);
                        } else {
                            new BukkitRunnable() {
                                @Override
                                public void run() {
                                    p.kickPlayer("§a[§a茶§b坂]§c密码错误！！！请稍后重试");
                                }
                            }.runTaskLater(plugin,10);
                        }
                    }else {
                        p.sendMessage("§a[§a茶§b坂]§c您还没有注册,请使用§a /reg [密码] [密码] §c来注册账号");
                    }

                }
            }


        }catch (Exception error){
            System.out.println("");
        }
        return true;
    }
}
